#!/bin/sh
# `csm` — the Claude Session Manager command line.
#
# This file ships INSIDE the app bundle (electron-builder `extraResources` puts
# it at <Resources>/bin/csm). What goes on your PATH is a SYMLINK to it, made by
# Settings -> Remote -> "Install the `csm` command". The link is deliberately the
# only thing outside the bundle:
#
#   - an app update replaces this script along with everything else, so the
#     command can never be older than the app it drives;
#   - nothing about the app's location is baked into the link, so there is no
#     copy on disk to go stale, and removing the link removes the command.
#
# ELECTRON_RUN_AS_NODE=1 runs the app's own Electron binary as plain Node, so
# `csm` needs no Node installed and no second runtime shipped. VS Code's `code`
# launcher and Orca's `orca` (MIT) both work this way; cli/ has no dependencies
# outside node: builtins, which is what makes it possible here.
set -e

# Walk the symlink chain back to this file inside the bundle. `readlink -f` would
# be shorter and is not portable: macOS's readlink has no -f.
self=$0
while [ -L "$self" ]; do
  link=$(readlink "$self")
  case $link in
    /*) self=$link ;;
    *) self=$(dirname "$self")/$link ;;
  esac
done
bin=$(CDPATH= cd -- "$(dirname -- "$self")" && pwd)
resources=$(dirname -- "$bin")
cli="$resources/cli/csm.mjs"

# macOS keeps the executable in Contents/MacOS; on Linux it sits beside
# resources/. Probing beats hardcoding a name electron-builder derives from
# productName and may sanitize differently per target.
app=$(dirname -- "$resources")
electron=
if [ -d "$app/MacOS" ]; then
  for candidate in "$app/MacOS/"*; do
    if [ -f "$candidate" ] && [ -x "$candidate" ]; then electron=$candidate; break; fi
  done
else
  for candidate in "claude-session-manager" "Claude Session Manager" "claudesessionmanager"; do
    if [ -f "$app/$candidate" ] && [ -x "$app/$candidate" ]; then electron="$app/$candidate"; break; fi
  done
fi

if [ -z "$electron" ]; then
  echo "csm: cannot find the Claude Session Manager binary near $resources." >&2
  echo "csm: if you moved or renamed the app, reinstall the command from Settings -> Remote." >&2
  exit 127
fi
if [ ! -f "$cli" ]; then
  echo "csm: cannot find the command line at $cli." >&2
  echo "csm: this app build does not ship it; update the app, or run it from a checkout." >&2
  exit 127
fi

# The user's NODE_OPTIONS is for THEIR node, not for an Electron running as one:
# --loader or --experimental-* aimed at a different runtime turns every csm
# invocation into a crash the user cannot connect to anything they did.
unset NODE_OPTIONS
ELECTRON_RUN_AS_NODE=1 exec "$electron" "$cli" "$@"
